<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Jobs\CalculateCommentLikesNumJob;
use App\Jobs\ImitateCircleJoinStepJob;
use App\Jobs\SubscribeMessageJob;
use App\Jobs\UserInputSafeCheckJob;
use App\Lib\WeApp\WeApp;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use App\Models\User\WxUserStudentCertify;
use App\Models\WxCommentLike;
use App\Models\User\WxUser;
use App\Wen\Utils\BaiduUtils;
use App\Wen\Utils\CommentUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class CommentController extends BaseController
{
    /**
     *  $posts_id 文章id
     *  $comment_id 评论id
     *  $user_id 评论的用户id
     *  $comment_content 评论内容
     * @param Request $request
     */
    public function add(Request $request)
    {
        global $__MINI_GLOBAL_CURRENT_PLAYER_ID__;
        $posts_id = $request->posts_id;
        $user_id = $request->uid;
        if(_empty_($posts_id) || _empty_($user_id)){
            return $this->fail(200001);
        }
        $posts_id = abs($posts_id);

        if(!UserUtils::is_user_can_speak($user_id)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$user_id
            ], '您当前处于禁言期间，无法言论');
        }

        $user = WxUser::find($user_id);
        if(_empty_($user)){
            return $this->fail(200000, [], '用户不存在');
        }

        if(mb_strlen( str_replace( [Settings::get('default_user_name', '微信用户'), '微信用户', '普通用户'], '', $user->user_name )) != mb_strlen($user->user_name)){
            return $this->fail(200041);
        }

        if(Settings::get('sticky_comment_force_bind_phone', 0, true) == 1){
            if(_empty_($user->phone) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未绑定手机号',
                    'content' => '前往绑定',
                    'confirmText' => '去绑定',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/editmine/editmine?phone=1'
                ], '未绑定手机号');
            }
        }

        if(Settings::get('sticky_comment_force_real_name', 0, true) == 1){
            if(_empty_($user->real_name) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未实名认证',
                    'content' => '您还没有实名认证，是否前往认证',
                    'confirmText' => '去认证',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/realname/realname'
                ], '未实名认证');
            }
        }

        $force_university = Settings::get('sticky_comment_force_university', [], true);
        if(!_empty_($force_university)){
            if(_empty_($user->university)){
                return $this->fail(200043, [
                    'title' => '未学生认证',
                    'content' => '您还没有学生认证，是否前往认证',
                    'confirmText' => '去认证',
                    'target_type' => 6,
                    'target_id' => '/pagesA/attestation/attestation'
                ], '未学生认证');
            }else{
                if(!in_array('-1', $force_university)){
                    $student_certify = WxUserStudentCertify::find($user->id);
                    if($student_certify){
                        if(!in_array($student_certify->sid, $force_university)){
                            return $this->fail(200000, [], '仅“'.Settings::get('sticky_comment_force_university_tip', '', true).'”可发布');
                        }
                    }
                }
            }
        }

        if(Settings::get('sticky_comment_force_subscribe_mp', 0, true) == 1){
            if(_empty_($user->weixin_mp_openid) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                $weapp = new WeApp('mp');
                $mpServicer = $weapp->getMpServicer();
                try {
                    $url = $mpServicer->getQrCodeWithPara(0, 'user:bind:'.$user->id);
                }catch (\Exception $e){
                    return $this->fail(200006, [], '生成公众号二维码失败，请检查[全局配置-支付-微信-公众号]');
                }
                if($url){
                    $qrCode = QrCode::format('png')->size(300)->generate($url);
                    $image = Image::make($qrCode);
                    $image->resizeCanvas(300, 300 + 60, 'bottom', false, '#ffffff'); // 增加高度，保持宽高比，背景色为白色
                    $mp_app_name = Settings::get('mp_app_name', '');
                    $text_tip = '关注'.$mp_app_name.'公众号，可以更方便通知到您';
                    if(mb_strlen($mp_app_name) > 4){
                        $text_tip = '关注'.$mp_app_name.'公众号';
                    }
                    $image->text($text_tip, 150, 40, function($font){
                        $font->file(public_path('storage/font/DingTalk_JinBuTi_Regular.ttf')); // 字体文件路径
                        $font->size(13); // 字体大小
                        $font->color('#000000'); // 字体颜色
                        $font->align('center'); // 水平对齐
                        $font->valign('top'); // 垂直对齐
                    });
                    $base64 = 'data:image/png;base64,' . base64_encode($image->encode('png')->getEncoded());
                    return $this->fail(200043, [
                        'title' => '未关注公众号，无法实时获取通知',
                        'content' => '前往关注',
                        'confirmText' => '去关注',
                        'target_type' => 26,
                        'target_id' => $base64
                    ], '未关注公众号');
                }
            }
        }

        if(Cache::has('user:comment:cahce:'.$user_id)){
            return $this->fail(200027);
        }
        _limit_user('add:comment', $user_id, 16);

        $reply_user_id = $request->input('reply_user_id', '');
        $comment_id = $request->input('comment_id', '');
        $comment_content = trim($request->comment_content ?? '');
        $comment_img_url = trim($request->comment_img_url);
        if(_empty_($request->giveCoin)){
            $giveCoin = 0;
        }else{
            $giveCoin = (int)($request->giveCoin);
        }

        $is_anonymous = _empty_default_($request->input('is_anonymous', 0), 0) == 1 ? 1 : 0;
        if($is_anonymous == 1 && Settings::get('app_vip_anonymous_only', 0) == 1){
            if($user->is_member){

            }else{
                return $this->fail(200043, [
                    'title' => '仅会员可用',
                    'content' => '匿名属于会员特权，是否前往开通',
                    'confirmText' => '前往开通',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/members/members'
                ], '仅会员可用');
            }
        }

        $device = in_array($request->header('device',''), ['app', 'h5', 'mp', 'pc']) ? $request->header('device','') : '';

        if($giveCoin == 0){
            if(_empty_($comment_content) && _empty_($comment_img_url)){
                return $this->fail(200001, [], '评论没有文字及图片');
            }

            if(UserUtils::user_permissions_check_by_config($user_id, 'audit_comment_white_list')){
                $need_manual_review = false;
            }else{
                // 百度审核
                $need_manual_review = true;
                $is_audit_comment = Settings::get('is_audit_comment');
                if ($is_audit_comment == 2) {
                    $filter_result = BaiduUtils::text_filter($comment_content);
                    if($filter_result){
                        if($filter_result['hit_level'] == 2){
                            // 不合规
                            return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                        }else if($filter_result['hit_level'] == 0){
                            // 审核通过
                            $need_manual_review = false;
                        }
                    }
                }else if($is_audit_comment == 0){
                    $need_manual_review = true;
                }else{
                    $need_manual_review = false;
                }
            }
            // 0:审核中，1:审核通过，2:驳回
            $comment_state = 1;
            if($need_manual_review){
                $comment_state = 0;
            }

        }else{
            $res_arr = UserUtils::give_coins($user_id, $giveCoin, $posts_id, $comment_id, $reply_user_id);
            if($res_arr['code'] != 200){
                return $this->fail($res_arr['code'], [], $res_arr['msg']);
            }
            $comment_state = 1;
            $comment_content = '<mini-icon name="mini-icon mini-jinbi2 gold-color"></mini-icon> 投了'.$giveCoin.'枚'.Settings::get('app_coin_name', '硬币'). '<mini-aite uid="'.$res_arr['to_user'].'" name="'.UserUtils::get_cached_user_name($res_arr['to_user']).'"></mini-aite>';
        }

        $r = WxCommentRepositores::add($posts_id, $comment_id,$reply_user_id, $user_id,  $comment_content, $comment_img_url, $comment_state, $device, $is_anonymous);
        if($r){
            if($comment_img_url){
                Utils::image_state_change([$comment_img_url], 1);
            }
            Redis::sadd('realtime:post:set', $posts_id);
            Redis::sadd('post:popular:comment:set', $posts_id);
            Cache::put('user:comment:cahce:'.$user_id, 1, 10);
            UserInputSafeCheckJob::dispatch($user_id, $comment_content);

            $tmplIds = [];
            if($device == 'mp'){
                $comment_reply_id = Settings::get('mini_template_message_comment_reply', '');
                if(!_empty_($comment_reply_id)){
                    $tmplIds[] = $comment_reply_id;
                }
            }


            if($comment_state == 1){
                if($giveCoin > 0){
                    SubscribeMessageJob::dispatch('gicecoin', $r);
                    return $this->success(['comment_id'=>$r, 'tip'=>$res_arr['msg']]);
                }else{
                    CalculateCommentLikesNumJob::dispatch($r);
                    if($comment_id && $comment_id > 0){
                        CalculateCommentLikesNumJob::dispatch($comment_id);
                    }

                    $circle_id = WxPost::where('id', $posts_id)->value('circle_id');
                    if($circle_id && $circle_id > 0){
                        ImitateCircleJoinStepJob::dispatch($circle_id, mini_rand(1, 100) <= 30 ? mini_rand(1, 2) : 0)->delay(now()->addMinutes(mini_rand(1, 20)));
                    }

                    SubscribeMessageJob::dispatch('comment_add', $r);
                    if($comment_id > 0){
                        SubscribeMessageJob::dispatch('comment_reply', $r);
                    }
                    $msg = UserUtils::reward_user_coin($user_id, 'comment');
                    if($msg){
                        UserUtils::assistant_notice($user_id, '您的评论(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">'.$r.'</a>)审核已通过，并获得评论奖励：'.$msg);
                        $postsUser_id = WxPost::where('id', $posts_id)->value('user_id');
                        
                        $commentDetails = CommentUtils::getCommentByCommentId($r, $user_id, $postsUser_id);
              // var_dump($commentDetails);die;
                        return $this->success(['comment_id'=>$commentDetails, 'tip'=>'您的评论审核已通过，并获得评论奖励：'.$msg, 'tmplIds'=>$tmplIds]);
                    }else{
                         $postsUser_id = WxPost::where('id', $posts_id)->value('user_id');
                        $commentDetails = CommentUtils::getCommentByCommentId($r, $user_id, $postsUser_id);
               //var_dump($commentDetails);die;
                        return $this->success(['comment_id'=>$commentDetails, 'tip'=>'您的评论审核已通过', 'tmplIds'=>$tmplIds]);
                    }
                }
            }else{
//                UserUtils::assistant_notice('admin', '有新发布的评论待审核，(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">进入笔记</a>)');
                UserUtils::assistant_notice_review(102, $r);
            }
            return $this->success(['comment_id'=>$r, 'tip'=>'评论成功，我们将尽快为您审核', 'tmplIds'=>$tmplIds]);
        }else{
            return $this->fail(200002);
        }
    }

    /**
     * 通过笔记获取评论列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCommentByPostsId(Request $request)
    {
        $posts_id = $request->posts_id;
        $uid = $request->uid;
        $comments = WxCommentRepositores::getCommentByPostsId($posts_id, $uid);
        return $this->success($comments);
    }

    /**
     * 通过评论id获取评论列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCommentByCommentId(Request $request)
    {
        $uid = $request->uid;
        $comment_id = $request->comment_id;
        $begin_id = $request->begin_id;

        if(_empty_($begin_id)){
            $begin_id = 0;
        }

        $childData = WxComment::where('comment_id', $comment_id)->where('comment_state', 1)->where('id', '>', $begin_id)
            ->orderBy('id', 'asc')->simplePaginate(10, FieldUtils::commentInfoColums());
        if($childData){
            $childData->map(function ($item) use ($uid) {
                $imgList = array();
                $item->comment_img_url = Utils::imgWithStyle($item->comment_img_url);
                if($item->comment_img_url){
                    array_push($imgList, ['img_url' => $item->comment_img_url]);
                }

                $item->is_like = WxCommentLike::where('comment_id', $item->id)->where('user_id', $uid)->exists();
                $item->like_count = WxCommentLike::where('comment_id', $item->id)->count();
                $item->imgList = $imgList;
                $item->user = UserUtils::get_cached_user($item->user_id);
                $item->comment_content_raw = strip_tags(_mini_phone(_mini_emoji(_mini_aite_replace($item->comment_content, true), true), true));
                $sub_allowable = [];
                if($uid > 0){
                    if($uid != $item->user_id) {
                        $sub_allowable[] = [
                            'text' => '举报',
                            'type' => 'report',
                            'id' => $item->id,
                            'icon' => 'mini-icon mini-jinggao'
                        ];
                    }
                    if($uid == $item->user_id || UserUtils::is_mini_admin($uid)){
                        $sub_allowable[] = [
                            'text' => '删除',
                            'type' => 'delete',
                            'id' => $item->id,
                            'icon' => 'mini-icon2 mini-shanchu'
                        ];
                    }
                }
                $sub_allowable[] = [
                    'text' => '复制',
                    'type' => 'copy',
                    'id' => $item->id,
                    'raw' => $item->comment_content_raw,
                    'icon' => 'mini-icon mini-fuzhi'
                ];
                $item->allowable = $sub_allowable;
                CommentUtils::anonymousProcess($item);
            });
            $childData->append(['format_time', 'ip_address']);
            return $this->success($childData);
        }
        return $this->fail(200003, [], '没有更多回复了');
    }

    /**
     * 点赞评论
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function commentAddLike(Request $request)
    {
        $uid = $request->uid;
        $comment_id = $request->comment_id;
        if(_empty_($comment_id)){
            return $this->fail(200001);
        }
        $res = CommentUtils::comment_like($uid, $comment_id);
        if($res > 0){
            return $this->success([],416003);
        }
        return $this->fail(200006);
    }

    /**
     * 删除评论
     * @param Request $request
     */
    public function delComment(Request $request)
    {
        $commentId = $request->id;
        $uid = $request->uid;

        $WxComment = WxComment::where('id',$commentId)->first();
        $posts_id = $WxComment->posts_id;
        if(_empty_($WxComment)){
            return $this->fail(200003);
        }
        $comment_user_id = $WxComment->user_id;
        // 权限验证
        if(!UserUtils::is_mini_admin($uid) && !($uid == $comment_user_id)){
            return $this->fail(200000, [], '删个屁啊，你都没有权限删除');
        }
        $comment_img_url = $WxComment->value('comment_img_url');

        if(false && $uid == $comment_user_id){
            WxComment::where('id', $commentId)
                ->update(['comment_content' => '（该评论已被自己删除）','comment_img_url' => '']);
        }else{
            WxComment::where('id',$commentId)->forceDelete();
            Cache::forget('post:commentCount:'.$posts_id);
        }

//        WxComment::where('comment_id',$commentId)->delete();
        if($comment_img_url){
            Utils::image_state_change([$comment_img_url], 0);
        }

        $popular_comment = json_decode(Cache::get('post:popular:comment:'.$posts_id, '[]'), true);
        if(_array_key($popular_comment, 'id', 0) == $WxComment->id){
            Cache::forget('post:popular:comment:'.$posts_id);
            Redis::sadd('post:popular:comment:set', $posts_id);
        }


        return $this->success();
    }

    /**
     * 置顶评论
     * @param Request $request
     */
    public function stickyComment(Request $request)
    {
        $commentId = $request->id;
        $uid = $request->uid;

        // 权限验证 管理员+文章作者
        if(!UserUtils::is_mini_admin($uid) && !(CommentUtils::get_comment_post_author($commentId) == $uid)){
            return $this->fail(200000, [], '你既不是管理员，也不是文章作者，你置顶个什么劲');
        }

        $comment = WxComment::find($commentId);
        if($comment){
            if($comment->is_sticky){
                $comment->is_sticky = 0;
                $r = $comment->save();
            }else{
                $comment->is_sticky = 1;
                $r = $comment->save();
            }
        }else{
            return $this->fail(200003);
        }
        if($r){
            return $this->success();
        }else{
            return $this->fail(200002);
        }

    }


}
